<template>
  <div id="login">
    <div v-if="isWechat">
      <div class="logo">
        <img src="../../static/img/logo.png" style="width: 2.67rem; height: 1.7rem; display: inline-block;">
      </div>
      <div class="login-form">
        <div class="fixed-login-form">
          <div><i class="icon icon-mobile"></i></div>
          <div class="flex-auto">
            <x-input v-model="formItem.phone" :max="11" type="tel" placeholder="请填写手机号码"></x-input>
          </div>
        </div>
        <div class="fixed-login-form">
          <div><i class="icon icon-lock"></i></div>
          <div class="flex-auto vux-1px-t"><x-input v-model="formItem.password" :max="16" type="password" placeholder="请填写6~16位密码"></x-input></div>
        </div>
      </div>
      <div style="margin-top: 0.35rem">
        <x-button type="primary" :show-loading="loading" action-type="button" @click.native="handleLogin">登录</x-button>
      </div>
      <div class="flex flex-space-between" style="margin-top: 0.3rem">
        <div class="text-orange" @click="showForget = true">忘记密码?</div>
        <div><router-link to="reg">新用户注册</router-link></div>
      </div>
      <actionsheet v-model="showForget" :menus="forgetMenus" @on-click-menu="handleForget" show-cancel></actionsheet>
      <div id="container" style="display:none;"></div>
    </div>
  </div>
</template>

<script>
import { XInput, XButton } from 'vux'
import { checkTel } from '../libs/fn'
import AMap from 'AMap'
export default{
  name: 'login',
  components: {
    XInput,
    XButton
  },
  beforeRouteEnter(to, from, next) {
    const ua = navigator.userAgent.toLowerCase();//获取判断用的对象
    //如果是微信页面登录且openid不存在，则获取openid，准备支付调起js支付时直接使用
    const {openid, unionid} = window.localStorage
    const isWechatBrowser = ua.match(/MicroMessenger/i) == "micromessenger"
//    if (isWechatBrowser && (!openid || !unionid)) {
    if (!openid || !unionid) {
//      window.location = $config.wechatHost + '/pay/wechat/wechat.php'
//      return
    }
    next()
  },
  mounted() {
    const u = navigator.userAgent;
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    this.formItem.os = isIOS ? 'ios': 'android'
  },
  created() {
    const {openid, unionid} = window.localStorage
    if(openid && unionid) {
      this.$http.post($config.host + '/api/Thirdpartylogin/thirdLogin', qs.stringify({
        union_id: unionid,
        client: $config.client_type,
        device: $config.device_type
      })).then((res) => {
        const {code, data, msg} = res.data
        if(code == 1) {
          data == 2? this.$router.push('bindUser'): this.handleWechatLogin()
        } else {
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.$vux.toast.text('登录失败', 'middle')
      })
    } else {
      this.getMapLocation()
      this.isWechat = true
    }
  },
  data() {
    return {
      isWechat: false,
      loading: false,
      showForget: false,
      forgetMenus: [{
        label: '找回密码',
        value: 'findPwd'
      }, {
        label: '手机验证码登录',
        value: 'codeLogin'
      }],
      formItem: {
        login_type: 1,
        phone: '',
        password: '',
        client: $config.client_type,
        device: $config.device_type,
        version: $config.version,
        device_name: 'wap',
        os: '',
        city_code: '',
        lng: '',
        lat: '',
        location: ''
      }
    }
  },
  methods: {
    getMapLocation(callback = () => {}) {
      var regmap, geolocation;
      //加载地图，调用浏览器定位服务
      regmap = new AMap.Map('container', {
        resizeEnable: true
      });
      regmap.plugin('AMap.Geolocation', () => {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 60000,          //超过10秒后停止定位，默认：无穷大
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          buttonPosition:'RB'
        });
        regmap.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', (data) => {
          const lnglatXY = [data.position.getLng(), data.position.getLat()]
          this.formItem.city_code = data.addressComponent.adcode
          this.formItem.lng = data.position.getLng()
          this.formItem.lat = data.position.getLat()
          var geocoder = new AMap.Geocoder({
            radius: 500,
            extensions: "all"
          });
          geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              this.formItem.location =  result.regeocode.formattedAddress
              callback()
            }
          });
        });
        AMap.event.addListener(geolocation, 'error', (data) => {

          AMap.plugin('AMap.CitySearch',() => {//异步
            let citysearch = new AMap.CitySearch();
            //自动获取用户IP，返回当前城市
            citysearch.getLocalCity((status, result) => {
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.city && result.bounds) {
                  this.formItem.city_code = result.adcode
                  const rectangle = result.rectangle.split(';')[0].split(',')
                  this.formItem.lng = rectangle[0]
                  this.formItem.lat = rectangle[1]
                  this.formItem.location = result.city
                  callback()
                }
              }
            })
          })
        });
      });
    },
    handleForget (key) {
      if(key != 'cancel' && key !== null && key !== undefined) {
          this.$router.push(key)
      }
    },
    setCache(data) {
      const isHttps = data.face.substring(0, 7)
      if(isHttps == 'http://'){
        data.face = data.face.replace(/http:\/\//, "https://")
      }
      let user = {
        uid: data.uid,
        phone: data.phone,
        status: data.status,
        token: data.token,
        verify_company: data.verify_company,
        verify_card: data.verify_card,
        verify_car: data.verify_car,
        verify_num: data.verify_num,
        service_id: data.service_id || '',
        level: data.level,
        fid: data.fid,
        nick_name: data.nick_name,
        face: data.face,
        //city_code: this.formItem.city_code,
        city_code: '420502',
        order_pai: data.order_pai,
        lng: data.lng,
        lat: data.lat,
        location: data.location
      }
      this.$store.commit('setUserInfo', user)
      //将登录数据保存在localStorage中
      window.localStorage.user = JSON.stringify(user)
    },
    handleWechatLogin() {
      this.getMapLocation(() => {
        const formItem = {
          client: $config.client_type,
          device: $config.device_type,
          version: $config.version,
          device_name: 'wap',
          os: 'wechat',
          city_code: this.formItem.city_code,
          lng: this.formItem.lng,
          lat: this.formItem.lat,
          location: this.formItem.location,
          open_id: window.localStorage.openid,
          union_id: window.localStorage.unionid,
          face: window.localStorage.face,
          nick_name: window.localStorage.nickname
        }
        this.$http.post($config.host + '/api/Thirdpartylogin/haveThird', qs.stringify(formItem)).then((res) => {
          const {code, data, msg} = res.data
          if(code == 1 && data) {
            this.setCache(data)
            // 跳转到登录前的页面
            let redirect = decodeURIComponent(this.$route.query.redirect || '/')
            this.$router.push({
              path: redirect
            })
          } else {
            this.$vux.toast.text(msg, 'middle')
          }
          this.loading = false
        }).catch((error) => {
            this.$vux.toast.text($config.errMsg, 'middle')
            this.loading = false
          })
      })

    },
    handleLogin() {
      if(this.formItem.city_code == '') {
        this.$vux.toast.text('正在获取你所在区域，请稍候登录', 'middle')
        return false
      }
      if(!checkTel(this.formItem.phone)) {
        this.$vux.toast.text('手机号码格式不正确', 'middle')
        return false
      }
      if(this.formItem.password.length < 6 || this.formItem.password.length > 16) {
        this.$vux.toast.text('请填写6~16位密码', 'middle')
        return false
      }
      this.loading = true

      this.$http.post($config.host + '/api/Userbase/login', qs.stringify(this.formItem))
        .then((res) => {
          const {code, data, msg} = res.data
          if(code == 1) {
            this.setCache(data)
            // 跳转到登录前的页面
            let redirect = decodeURIComponent(this.$route.query.redirect || '/')
            this.$router.push({
              path: redirect
            })
          } else {
            this.$vux.toast.text(msg, 'middle')
          }
          this.loading = false
        })
        .catch((error) => {
          this.$vux.toast.text($config.errMsg, 'middle')
          this.loading = false
        })
    }
  },
  beforeRouteLeave(to, from, next) {
    this.formItem = {
      login_type: 1,
      phone: '',
      password: '',
      client: $config.client_type,
      device: $config.device_type,
      version: $config.version,
      device_name: 'wap',
      os: '',
      city_code: '',
      lng: '',
      lat: '',
      location: ''
    }
    next()
  }
}
</script>

<style scoped>
  #login{
    padding: 0 0.2rem;
  }
  .logo{
    height: 1.8rem;
    margin-top: 1rem;
    margin-bottom: 0.65rem;
    text-align: center;
  }
  .login-form{
    background: #fff;
    height: auto;
    box-shadow: 0px 0px 0.1rem rgba(0, 0, 0, 0.05);
  }
  .fixed-login-form{
    display: flex;
    align-items: center;
  }
  .fixed-login-form .icon{
    width: 0.5rem;
    text-align: center;
    display: inline-block;
    margin-left: 0.15rem;
  }
</style>
